<template>
  <div class="mod-config">
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item>
        <el-input
          v-model="dataForm.key"
          placeholder="参数名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
        <el-button
          type="danger"
          @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0"
          >批量删除</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
      >
      </el-table-column>
      <el-table-column
        prop="brandId"
        header-align="center"
        align="center"
        label="品牌id"
      >
      </el-table-column>
      <el-table-column
        prop="name"
        header-align="center"
        align="center"
        label="品牌名"
      >
      </el-table-column>
      <el-table-column
        prop="logo"
        header-align="center"
        align="center"
        label="品牌logo地址"
      >
        <template slot-scope="scope">
          <!-- <el-image
            style="width: 100px; height: 80px"
            :src="scope.row.logo"
            fit="scale-down"
          ></el-image> -->
          <img :src="scope.row.logo" style="width: 100px; height: 80px" />
        </template>
      </el-table-column>
      <el-table-column
        prop="descript"
        header-align="center"
        align="center"
        label="介绍"
      >
      </el-table-column>
      <el-table-column
        prop="showStatus"
        header-align="center"
        align="center"
        label="显示状态"
      >
        <!--用scope机制，注入一个switch开关进来-->
        <template slot-scope="scope">
          <!--这个开关双向绑定的值就是scope所在数据包的对应数据，
                  这里也就是显示状态这一栏的showStatus属性。
                  用scope.row.showStatus来获取这个值-->
          <el-switch
            v-model="scope.row.showStatus"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            @change="showStatusChange(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="firstLetter"
        header-align="center"
        align="center"
        label="检索首字母"
      >
      </el-table-column>
      <el-table-column
        prop="sort"
        header-align="center"
        align="center"
        label="排序"
      >
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="updateCatelogHandle(scope.row.brandId)"
            >关联分类</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="addOrUpdateHandle(scope.row.brandId)"
            >修改</el-button
          >
          <el-button type="text" size="small" @click="deleteHandle(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getDataList"
    ></add-or-update>

    <el-dialog
      title="关联分类"
      :visible.sync="cateRelationDialogVisible"
      width="30%"
    >
      <el-popover placement="right-end" v-model="popCatelogSelectVisible">
        <category-cascader :catelogPath.sync="catelogPath"></category-cascader>
        <div style="text-align: right; margin: 0">
          <el-button
            size="mini"
            type="text"
            @click="popCatelogSelectVisible = false"
            >取消</el-button
          >
          <el-button type="primary" size="mini" @click="addCatelogSelect"
            >确定</el-button
          >
        </div>
        <el-button slot="reference">新增关联</el-button>
      </el-popover>
      <!--注意，cateRelationTableData是整个Entity
        但是，prop可以自动从这个Entity中寻找到指定字段名称的值
        这里也就是brandName和catelogName的值-->
      <el-table :data="cateRelationTableData" style="width: 100%">
        <el-table-column prop="id" label="#"></el-table-column>
        <el-table-column prop="brandName" label="品牌名"></el-table-column>
        <el-table-column prop="catelogName" label="分类名"></el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="deleteCateRelationHandle(scope.row.id, scope.row.brandId)"
              >移除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cateRelationDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="cateRelationDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  brandList,
  brandUpdateStatus,
  brandDelete,
  categoryBrandRelationSave,
  categoryBrandRelationDelete,
  categoryBrandRelationList,
} from "@/api/mall/brand";
import { ossMultiDelete } from "@/api/mall/thirdparty";
import AddOrUpdate from "./brand-add-or-update";
import CategoryCascader from "../../mall/common/category-cascader.vue";

export default {
  data() {
    return {
      dataForm: {
        key: "",
      },
      brandId: 0,
      catelogPath: [],
      dataList: [],
      cateRelationTableData: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      cateRelationDialogVisible: false,
      popCatelogSelectVisible: false,
    };
  },
  components: {
    AddOrUpdate,
    CategoryCascader,
  },
  activated() {
    this.getDataList();
  },
  methods: {
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      var Params = {
        page: this.pageIndex,
        limit: this.pageSize,
        key: this.dataForm.key,
      };
      brandList(Params).then((data) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },

    showStatusChange(rowStatus) {
      console.log("最新状态", rowStatus);
      var Entity = {
        brandId: rowStatus.brandId,
        showStatus: rowStatus.showStatus * 1,
      };
      brandUpdateStatus(Entity).then((data) => {});
      if (rowStatus.showStatus == true) {
        this.$message({
          message: "开启显示",
          type: "success",
        });
      } else {
        this.$message({
          message: "关闭显示",
          type: "success",
        });
      }
    },

    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选，会把选中的这一行放到dataListSelections数组中
    // 注意，每一个val都是一个BrandEntity
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
    },
    // 删除
    deleteHandle(entity) {
      // 批量删除时，调用该方法传入的entity是空
      // 单行删除时，调用该方法传入的entity是对应行的entity
      // 所以判断传入参数entity是否为空，来判断是批量删除还是单行删除
      var ids = entity
        ? [entity.brandId]
        : this.dataListSelections.map((item) => {
            return item.brandId;
          });
      // 注意怎样在批量删除的情况下构建ids数组
      // dataListSelection中保存多选的BrandEntity，提取出BrandEntity的brandId做成数组
      // 因为后端要求前端提交的json中存放一个数组
      // 参照这个思路，完全可以在做一个logos数组存放logo地址。
      var logos = entity
        ? [entity.logo.substr(entity.logo.lastIndexOf(".com/") + 5)]
        : this.dataListSelections.map((item) => {
            return item.logo.substr(item.logo.lastIndexOf(".com/") + 5);
          });
      console.log(logos);
      this.$confirm(
        `确定对[id=${ids.join(",")}]进行[${entity ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        brandDelete(ids).then((data) => {
          // 数据库成功删除后再将OSS中的内容删除
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              },
            });
            ossMultiDelete(logos).then((data) => {});
            // 如果数据库删除失败就弹出错误信息
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    },
    // 级联分类的相关方法代码
    addCatelogSelect() {
      //{"brandId":1,"catelogId":2}
      this.popCatelogSelectVisible = false;
      var idjson = {
        brandId: this.brandId,
        catelogId: this.catelogPath[this.catelogPath.length - 1],
      };
      categoryBrandRelationSave(idjson).then((data) => {
        this.getCateRelation();
      });
    },
    deleteCateRelationHandle(id, brandId) {
      var idjson = {
        ids: [id],
      };
      categoryBrandRelationDelete(idjson).then((data) => {
        this.getCateRelation();
      });
    },
    updateCatelogHandle(brandId) {
      this.cateRelationDialogVisible = true;
      this.brandId = brandId;
      this.getCateRelation();
    },
    getCateRelation() {
      var params = {
        brandId: this.brandId,
      };
      categoryBrandRelationList(params).then((data) => {
        this.cateRelationTableData = data.CBRelation;
      });
    },
  },
};
</script>